package edu.qust.y22.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import edu.qust.y22.bean.Admin;
import edu.qust.y22.constant.ErrorEnum;
import edu.qust.y22.constant.Message;
import edu.qust.y22.service.AdminService;

@RestController
@RequestMapping("common")
public class CommonController {
	
	@Autowired
	private AdminService adminService;
	
	@Autowired
	private HttpServletRequest httpRequest;
	
	@RequestMapping("login")
	public Message login(@RequestBody Admin loginAdmin) {
		
		Admin admin = this.adminService.selectByUserName(loginAdmin.getUserName());
		if(admin == null) {
			return Message.createFailureMessage(ErrorEnum.UnknownAccount);
		}
		if(!admin.getPassword().equals(loginAdmin.getPassword())){
			return Message.createFailureMessage(ErrorEnum.IncorrectCredentials);
		}
		
		HttpSession session = httpRequest.getSession(true);
		session.setAttribute("LOGIN",loginAdmin.getUserName());
		
		return Message.createSuccessMessage(loginAdmin.getUserName());
	}
	
	@RequestMapping("seeklogin")
	public Message seeklogin() {
		
		HttpSession session = httpRequest.getSession(true);
		String name = (String)session.getAttribute("LOGIN");
		
		if(session.getAttribute("LOGIN")==null) {
			return Message.createFailureMessage(ErrorEnum.Unlogin);
		}
		return Message.createSuccessMessage(name);
	}
	
	@RequestMapping("logon")
	public Message logon(@RequestBody Admin logonAdmin) {
		int success = this.adminService.insert(logonAdmin);
		if(success == 1){
			return Message.createSuccessMessage();
		}else{
			return Message.createFailureMessage(ErrorEnum.UnkonwError);
		}
	}
	
	@RequestMapping("dellogin")
	public Message dellogin(@RequestBody Admin admin) {
		
		HttpSession session = httpRequest.getSession(true);
		session.removeAttribute("LOGIN");
		if(session.getAttribute("LOGIN")==null) {
			return Message.createSuccessMessage();
		}
		return Message.createFailureMessage(ErrorEnum.UnkonwError);
	}
}
